/**
 * Copyright (C) 2012 The SkyTvOS Project
 * <p/>
 * Version     Date           Author
 * ─────────────────────────────────────
 * 2014年12月27日         Root.Lu
 */

package com.coocaa.launcher.statusplugins.weather;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.coocaa.launcher.framework.launcherhost.statusbar.StatusBarPlugin;
import com.coocaa.launcher.framework.launcherhost.statusbar.StatusBarPluginView;
import com.coocaa.x.framework.app.BootUpRunnable;
import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.utils.Android;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.XServiceManager;
import com.skyworth.logsdk.appstore.LogAPIForAppStore;
import com.skyworth.webSDK.webservice.weather.domian.DayWeather;
import com.skyworth.webSDK.webservice.weather.domian.WeatherInfo;
import com.skyworth.webSDK.webservice.weather.service.WeatherService;

import java.util.List;

public class StatusPluginWeather extends StatusBarPlugin {
    public interface IStatusPluginWeather {
        void update(String location, List<DayWeather> weather);
        void changeView(boolean isVisible);
    }

    public static StatusPluginWeather instance = new StatusPluginWeather();
    private StatusBarPluginView view = null;
    private IStatusPluginWeather weather = null;

    public StatusPluginWeather() {
        super("statusplugin.weather");
        // TODO Auto-generated constructor stub
    }

    private Runnable runnable = new Runnable() {
        private String city = null;

        private String getCity() {
            try {
                String location = XServiceManager.getLiteCCConnectorService().getLocation();
                String[] locations = location.split(",");
                city = locations[1];
            } catch (Exception e) {
            }
            if (city == null) {
                WeatherService weatherService = CoocaaApplication.getCoocaaWebService()
                        .getWeatherService();
                try {
                    city = weatherService.getAddress();
                } catch (Exception e) {
                    LogAPIForAppStore.reportInterfaceError("获取城市", Android.throwable2String(e));
                }
                String[] citys = city.split(",");
                city = citys[citys.length - 1];
            }
            LogUtils.d(getName() + "sunny getCity city1:" + city);
            return city;
        }

        public void run() {
            while (true) {
                try {
                    final String city = getCity();
                    final List<DayWeather> dayWeather = getDayWeather();
                    LogUtils.d(getName() + "sunny getCity city2:" + city + ";  "+dayWeather);
                    if (weather != null && dayWeather != null  && city != null && !city.equals(""))
                        weather.update(city, dayWeather);
                    break;
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                }
            }

            ConnectivityManager connectivityManager = (ConnectivityManager) mContext
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = connectivityManager.getActiveNetworkInfo();
            if (info != null && info.isAvailable() && info.isConnected()) {
                if (weather != null)
                    weather.changeView(true);
            } else {
                if (weather != null)
                    weather.changeView(false);
            }
            // clearAction(runnable);
            postAction(runnable, 1000 * 60 * 60 * 2);
        }

        private List<DayWeather> getDayWeather() throws Exception {
            WeatherService weatherService = CoocaaApplication.getCoocaaWebService()
                    .getWeatherService();
            try {
                WeatherInfo info = weatherService.GetWeather(city);
                if (info == null)
                    return null;
                return info.days;
            } catch (Exception e) {
                LogAPIForAppStore.reportInterfaceError("获取天气", Android.throwable2String(e));
                throw e;
            }
        }
    };

    @Override
    protected void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        try{
            IntentFilter mFilter = new IntentFilter();
            mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            mFilter.addAction("SYS_EVN_CHANGE");
            mFilter.addAction(BootUpRunnable.QUICK_RESUME_ACTION);
            mContext.registerReceiver(mReceiver, mFilter);
        }catch (Exception e){
            e.printStackTrace();
        }
        LogUtils.d(getName() + "sunny getCity onCreate:");
        postAction(runnable, 1000);
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        try{
             mContext.unregisterReceiver(mReceiver);
        }catch (Exception e){
            e.printStackTrace();
        }
        super.onDestroy();
        ((StatusPluginWeatherView) view).destroy();
        view = null;
        weather = null;
    }

    @Override
    public StatusBarPluginView inflate(String pattern) {
        // TODO Auto-generated method stub
        if (view == null) {
            view = new StatusPluginWeatherView(mContext, getName());
            weather = (IStatusPluginWeather) view;
        }
        return view;
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION) || action.equals("SYS_EVN_CHANGE")) {
                postAction(runnable, 1000);
            } else if (action.equals(BootUpRunnable.QUICK_RESUME_ACTION)) {
                postAction(runnable, 1000 * 60 * 2);
            }
        }
    };
}
